import { StyleSheet, Text, View, FlatList, Pressable } from 'react-native';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import { appStore, deviceStore, observer } from '~/store';
import { NavBarHeader, ContentStatus, DialogModal } from '~/components';
import { getUserOfflineCourse, updateUserCourseStatus, offlinePauseCourse } from '~/api/deviceApi';
import {
    getBleCurrentCourse,
    getLaserTreatmentParameterOnline,
    setLaserTimeOut,
    switchBleOfflineCourse,
    getBleCourseOffline,
} from '~/utils/ble/application';
import { px2dp, scale } from '~/utils/px2dp';

export default observer(() => {
    const navigation: any = useNavigation();
    const { t } = useTranslation();
    const { device, currentBleCourseSn, bleDeviceCourseStatus } = deviceStore;
    const [listData, setListData] = useState([]);
    const [remainingDays, setRemainingDays] = useState(0);
    const [isRefreshing, setIsRefreshing] = useState(false); // 是否刷新
    const getData = () => {
        getUserOfflineCourse({ title_id: 24, device_sn: device.connectDevice.device_sn }).then(async (res) => {
            const { course_data, remaining_days, status, code } = res;
            setIsRefreshing(false);
            if (status == 1 && code == 200) {
                deviceStore.courseOfflineDataLength = course_data.length;
                deviceStore.isWriteOffline = true;
                setListData(course_data);
                setRemainingDays(remaining_days);
            } else {
                setListData([]);
                setRemainingDays(0);
            }
        });
    };
    const [visible, setVisible] = useState(false);
    const [selectInfo, setSelectInfo] = useState({ course_type_sn: '', user_course_id: '', course_id: '' });
    const onConfirm = () => {
        switchBleOfflineCourse(selectInfo.course_type_sn);
        setVisible(false);
        deviceStore.offlineActionType = 'switch';
        getBleCurrentCourse();

        updateUserCourseStatus({
            user_course_id: selectInfo.user_course_id,
            device_sn: device.connectDevice.device_sn,
            type: 1,
            course_id: selectInfo.course_id,
        }).then((res) => {
            console.log('切换疗程成功', res);
        });
    };
    const courseDetailes = (item) => {
        navigation.navigate('MyCourseDetailes', {
            device_sn: device.connectDevice.device_sn,
            user_course_id: item?.course_id,
            type: 1,
        });
    };
    const renderItem = ({ item }) => {
        return (
            <View style={[styles.listItem]}>
                <View style={styles.row}>
                    <Text style={styles.courseTitle}>
                        {appStore.app.language == 'zh'
                            ? item?.course_name
                            : item.en_course_name
                            ? item.en_course_name
                            : item?.course_name}
                    </Text>
                    <Pressable
                        style={[
                            styles.row,
                            styles.bt,
                            currentBleCourseSn == item.course_type_sn && { backgroundColor: '#eee' },
                        ]}
                        onPress={() => {
                            if (currentBleCourseSn == item.course_type_sn) {
                                return;
                            }
                            setSelectInfo(item);
                            setVisible(true);
                        }}>
                        <Text style={[styles.bt_text, currentBleCourseSn == item.course_type_sn && { color: '#000' }]}>
                            {currentBleCourseSn == item.course_type_sn
                                ? t('HealthOfflineManagement.t1')
                                : t('HealthOfflineManagement.t2')}
                        </Text>
                    </Pressable>
                </View>
                <Pressable
                    style={[styles.row, { justifyContent: 'flex-start', marginTop: px2dp(12) }]}
                    onPress={() => courseDetailes(item)}>
                    <Text style={styles.detailes}>{t('HealthOfflineManagement.t3')}</Text>
                    <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#a4a4a4'}></Icon>
                </Pressable>
            </View>
        );
    };
    const handleRefresh = () => {
        getData();
        setIsRefreshing(true);
    };
    const [visible1, setVisible1] = useState(false);
    const stopCourse = () => {
        deviceStore.offlineActionType = 'stop';
        setLaserTimeOut(0);
        const courseTypeSnStr = listData.map((item: any) => item.course_type_sn).join(',');
        offlinePauseCourse({ user_course_id: courseTypeSnStr, device_sn: device.connectDevice.device_sn });
        setTimeout(() => {
            getBleCourseOffline();
        }, 300);
        setVisible1(false);
    };
    const startCourse = async () => {
        deviceStore.offlineActionType = 'open';
        deviceStore.isWriteOffline = false;
        setLaserTimeOut(1);
        getLaserTreatmentParameterOnline();
        setTimeout(() => {
            getBleCourseOffline();
        }, 300);
        setVisible1(false);
    };
    const onConfirm1 = () => {
        if (bleDeviceCourseStatus == 2) {
            startCourse();
        } else {
            stopCourse();
        }
    };
    useEffect(() => {
        deviceStore.offlineActionType = 'switch';
        getBleCurrentCourse();
        setTimeout(() => {
            getBleCourseOffline();
        }, 300);
        getData();
    }, []);

    return (
        <View style={styles.container}>
            <NavBarHeader title={t('HealthOfflineManagement.t4')} />
            <FlatList
                ListHeaderComponent={
                    <>
                        {listData.length > 0 && (
                            <View style={styles.card}>
                                <View style={styles.row}>
                                    <Text>{t('HealthOfflineManagement.t5')}</Text>
                                    <Pressable
                                        style={[
                                            styles.row,
                                            styles.bt,
                                            bleDeviceCourseStatus == 1 && { backgroundColor: '#1877FF' },
                                        ]}
                                        onPress={() => {
                                            setVisible1(true);
                                        }}>
                                        <Text style={styles.bt_text}>
                                            {bleDeviceCourseStatus == 1
                                                ? t('HealthOfflineManagement.t9')
                                                : t('HealthOfflineManagement.t6')}
                                        </Text>
                                    </Pressable>
                                </View>
                                <Text>
                                    {t('HealthOfflineManagement.t7')}：{remainingDays}
                                </Text>
                            </View>
                        )}
                    </>
                }
                contentContainerStyle={styles.contentContainerStyle}
                showsVerticalScrollIndicator={false}
                data={listData}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
                onEndReachedThreshold={0.1}
                onRefresh={handleRefresh}
                refreshing={isRefreshing}
                ListEmptyComponent={() => <ContentStatus status="empty" source={{ title: t('CourseList.t4') }} />}
            />
            <DialogModal
                key={'switch'}
                visible={visible}
                content={t('HealthOfflineManagement.t8')}
                onCancel={() => setVisible(false)}
                onConfirm={onConfirm}
            />
            <DialogModal
                key={'start'}
                visible={visible1}
                content={
                    bleDeviceCourseStatus == 2 ? t('HealthOfflineManagement.t10') : t('HealthOfflineManagement.t11')
                }
                onCancel={() => setVisible1(false)}
                onConfirm={onConfirm1}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },

    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
        marginHorizontal: px2dp(24),
    },
    card: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        marginTop: px2dp(24),
        borderRadius: px2dp(24),
    },
    listItem: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        marginTop: px2dp(24),
        borderRadius: px2dp(24),
    },
    courseTitle: {
        fontSize: scale(28),
        color: '#000',
        width: '70%',
        lineHeight: px2dp(40),
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    bt: {
        backgroundColor: '#242D56',
        width: px2dp(160),
        height: px2dp(60),
        borderRadius: px2dp(40),
        justifyContent: 'center',
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(28),
    },
    detailes: {
        color: '#a4a4a4',
        fontSize: scale(28),
    },
});
